<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="备份周期" prop="cron.cycle">
          <el-select
            v-model="cron.cycle"
            placeholder="备份周期"
            style="width: 80px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.CMS_DBBACKUP_CYCLE)"
              :label="dict.label"
              :key="dict.label"
              :value="dict.value"
            />
          </el-select>
          <template v-if="cron.cycle=='yearly'" >
            <el-input-number v-model="cron.month" placeholder="月"  type="integer" :min="1" :max="12" />月
          </template>
          <template v-if="cron.cycle=='yearly'||cron.cycle=='monthly'"><el-input-number v-model="cron.day" placeholder="日" :min="1" :max="31" />日</template>
          <template v-if="cron.cycle=='weekly'">
            <el-select
              v-model="cron.weekday"
              placeholder="周" style="width: 80px"
            >
              <el-option
                v-for="dict in weeklyList"
                :label="dict.label"
                :key="dict.label"
                :value="dict.value"
              />
          </el-select>
        </template>
        <el-input v-model="cron.time" placeholder="时间"  type="time" style="width: 120px"  />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button :disabled="formLoading" type="danger" @click="deleteTask">删 除</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as DataBackupApi from '@/api/infra/dbbackup'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

defineOptions({ name: 'DbBackupTaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('定时备份') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref<DataBackupApi.DbBackupTaskVO>({
  id: undefined,
  cron: ''
})
const weeklyList = ref([
    { label: '周一', value: '2' },
    { label: '周二', value: '3' },
    { label: '周三', value: '4' },
    { label: '周四', value: '5' },
    { label: '周五', value: '6' },
    { label: '周六', value: '7' },
    { label: '周日', value: '1' },
])
const cron = ref({
  cycle: 'daily',
  month: '1',
  weekday: '2',
  day: '1',
  time: '00:00:00',
})
const formRules = reactive({
  id: [{ required: true, message: '数据库不能为空', trigger: 'blur' }],
  cron: [{ required: true, message: '定时任务设置不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value.id = id
      const taskRes = await DataBackupApi.getTaskById(id)
      //解析到设置
      if(taskRes&&taskRes.cron){
        formData.value = taskRes
        parseCron()
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as DataBackupApi.DbBackupTaskVO
    console.log(data)
    //转cron表达式
    toCron()
    await DataBackupApi.saveTask(data)
    message.success(t('common.success'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const deleteTask = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 删除的二次确认
    await message.delConfirm()
    await DataBackupApi.deleteTask(formData.value.id)
    message.success(t('common.delSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 转cron表达式
const toCron = () => {
      const cycle = cron.value.cycle
      const month = cron.value.month
      const weekday = cron.value.weekday
      const day = cron.value.day
      const time = cron.value.time
      const timeList = time.split(":");
      const hour = timeList[0]
      const minute = timeList[1]
      //const second = timeList[2]

      switch(cycle) {
        case 'yearly':
          // 每年
          formData.value.cron = `0 ${minute} ${hour} ${day} ${month} ?`;
          return;
        case 'monthly':
          // 每月
          formData.value.cron = `0 ${minute} ${hour} ${day} * ?`;
          return;
        case 'weekly':
          formData.value.cron = `0 ${minute} ${hour} ? * ${weekday}`;
          return;
        case 'daily':
          // 每日
          formData.value.cron = `0 ${minute} ${hour} * * ?`;
          return;
        default:
          throw new Error('不支持的类型');
      }
}
    // 解析cron表达式
const  parseCron = () => {
      const parts = formData.value.cron.split(' ');
      if (parts.length !== 6 && parts.length !== 7) {
        return;
      }
      const [second, minute, hour, day, month, dayOfWeek, year] = parts;
      let cycle;
      if (month !== '*' && day !== '*' && dayOfWeek === '?') {
        cycle = 'yearly';
      } else if (month === '*' && day !== '*' && dayOfWeek === '?') {
        cycle = 'monthly';
      } else if (month === '*' && day === '?' && dayOfWeek !== '*') {
        cycle = 'weekly';
      } else if (month === '*' && day === '*' && dayOfWeek === '?') {
        cycle = 'daily';
      }
      cron.value = {
        cycle: cycle,
        month: cycle === 'daily' || cycle === 'monthly' || cycle === 'weekly' ? '' : month,
        day: cycle === 'daily' || cycle === 'weekly' ? '' : day,
        weekday: cycle === 'weekly' ? dayOfWeek : '',
        time: hour + ":" + minute 
      }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    cron: ''
  }
  formRef.value?.resetFields()
}
</script>
